package com.atguigu.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.atguigu.gulimall.order.pay.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderResponseVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    @Autowired
    AlipayTemplate alipayTemplate;


    @GetMapping("/confirm")
    public String toConfirm(Model model) throws Exception {
        OrderConfirmVo orderConfirmVo = orderService.getConfirmInfo();
        model.addAttribute("confirmOrderData", orderConfirmVo);

        return "confirm";
    }


    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) throws Exception {
        OrderResponseVo orderResponseVo = orderService.submitOrder(orderSubmitVo);
        //描述错误信息的msg
        String msg = "";
        Integer code = orderResponseVo.getCode();
        if (code == 0) {
            model.addAttribute("orderResp", orderResponseVo);
            //订单提交成功
            return "pay";
        } else {
            switch (code) {
                case 1:
                    msg += "token校验失败，请刷新页面后重试";
                    break;
                case 2:
                    msg += "验证价格失败";
                    break;
                case 3:
                    msg += "扣除库存失败";
                    break;
            }
            //跳回到原来的页面
            redirectAttributes.addFlashAttribute("msg", msg);

            return "redirect:http://order.gulimall.com/confirm";
        }
    }

    /**
     * @param orderSn 支付的时候携带的订单号
     * @return
     */
    @GetMapping(value = "/orderPay", produces = "text/html")
    @ResponseBody
    public String orderPay(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getOrderPay(orderSn);
        String result = alipayTemplate.pay(payVo);
        System.out.println(result);
        return result;
    }




}
